package com.freesky.biz.icbc.controller;

import com.freesky.biz.icbc.domain.TScanUser;
import com.freesky.biz.icbc.service.IScanChannelService;
import com.freesky.common.annotation.Log;
import com.freesky.common.annotation.RepeatSubmit;
import com.freesky.common.core.controller.BaseController;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.core.domain.entity.TScanChannel;
import com.freesky.common.core.page.TableDataInfo;
import com.freesky.common.enums.BusinessType;
import com.freesky.common.utils.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 线下扫码业务
 */
@RestController
@RequestMapping("/icbc/scanchannel")
public class ScanChannelController extends BaseController {

    @Autowired
    private IScanChannelService scanChannelService;

    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('icbc:scanchannel:export')")
    @GetMapping("/export")
    public AjaxResult export(TScanChannel scanChannel,
                             HttpServletResponse response) {
        return scanChannelService.exportFile(scanChannel);
    }

    /**
     * 获取扫码通道列表
     */
    @PreAuthorize("@ss.hasPermi('icbc:scanchannel:list')")
    @GetMapping("/list")
    public AjaxResult list(TScanChannel scanChannel) {
        List<TScanChannel> depts = scanChannelService.selectScanChannelList(scanChannel);
        return success(depts);
    }

    @PreAuthorize("@ss.hasPermi('icbc:scanchannel:list')")
    @GetMapping("/page")
    public TableDataInfo page(TScanChannel scanChannel) {
        startPage();
        List<TScanChannel> depts = scanChannelService.selectScanChannelList(scanChannel);
        return getDataTable(depts);
    }

    /**
     * 查询扫码通道列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('icbc:scanchannel:list')")
    @GetMapping("/list/exclude/{channelId}")
    public AjaxResult excludeChild(@PathVariable(value = "channelId", required = false) Long channelId)
    {
        List<TScanChannel> depts = scanChannelService.selectScanChannelList(new TScanChannel());
        depts.removeIf(d -> d.getChannelId().intValue() == channelId || ArrayUtils.contains(StringUtils.split(d.getPids(), ","), channelId + ""));
        return success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('icbc:scanchannel:query')")
    @GetMapping(value = "/{channelId}")
    public AjaxResult getInfo(@PathVariable Long channelId) {
        return success(scanChannelService.selectScanChannelById(channelId));
    }

    /**
     * 新增渠道管理
     */
    @PreAuthorize("@ss.hasPermi('icbc:scanchannel:add')")
    @Log(title = "渠道管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody TScanChannel scanChannel)
    {
        if (!scanChannelService.checkScanChannelNameUnique(scanChannel))
        {
            return error("新增渠道'" + scanChannel.getChannelName() + "'失败，渠道名称已存在");
        }
        scanChannel.setCreateBy(String.valueOf(getUserId()));
        return toAjax(scanChannelService.insertScanChannel(scanChannel));
    }

    /**
     * 修改渠道
     */
    @PreAuthorize("@ss.hasPermi('icbc:scanchannel:edit')")
    @Log(title = "渠道管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody TScanChannel scanChannel)
    {
        Long deptId = scanChannel.getChannelId();
        if (!scanChannelService.checkScanChannelNameUnique(scanChannel)) {
            return error("修改渠道'" + scanChannel.getChannelName() + "'失败，渠道名称已存在");
        }
        else if (scanChannel.getPid().equals(String.valueOf(deptId)))
        {
            return error("修改渠道'" + scanChannel.getChannelName() + "'失败，上级渠道不能是自己");
        }
        scanChannel.setUpdateBy(String.valueOf(getUserId()));
        return toAjax(scanChannelService.updateScanChannel(scanChannel));
    }

    /**
     * 删除渠道
     */
    @PreAuthorize("@ss.hasPermi('icbc:scanchannel:remove')")
    @Log(title = "渠道管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{channelId}")
    public AjaxResult remove(@PathVariable Long channelId) {
        if (scanChannelService.hasChildByScanChannelId(channelId))
        {
            return warn("存在下级渠道,不允许删除");
        }
        if (scanChannelService.checkScanChannelExistUser(channelId))
        {
            return warn("渠道存在用户,不允许删除");
        }
        scanChannelService.deleteScanChannelById(channelId);
        return toAjax(1);
    }

    @PreAuthorize("@ss.hasPermi('icbc:scanchannel:list')")
    @GetMapping("/channelTree")
    public AjaxResult channelTree(TScanChannel scanChannel) {
        return success(scanChannelService.selectScanChannelTreeList(scanChannel));
    }
}
